using AutoMapper;
using B.S.NewMedical.Api.Write.Application.Command.MobileService.Consult;
using B.S.NewMedical.Domain.MobileService;
using B.S.NewMedical.ErrorCode;
using B.S.NewMedical.Infrastructure.Interface;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.NewMedical.Api.Write.Application.Handler.MobileService.Consult
{
    /// <summary>
    /// 创建用户互动（点赞/收藏/追问）处理器
    /// </summary>
    public class CreateConsultInteractHandler : IRequestHandler<CreateConsultInteractCommand, ApiResult<bool>>
    {
        private readonly IBaseRepository<ConsultInteract> _interactRepository;
        private readonly IBaseRepository<ConsultQuestion> _questionRepository;
        private readonly IBaseRepository<ConsultAnswer> _answerRepository;
        private readonly ILogger<CreateConsultInteractHandler> _logger;
        private readonly IMapper _mapper;

        public CreateConsultInteractHandler(
            IBaseRepository<ConsultInteract> interactRepository,
            IBaseRepository<ConsultQuestion> questionRepository,
            IBaseRepository<ConsultAnswer> answerRepository,
            ILogger<CreateConsultInteractHandler> logger,
            IMapper mapper)
        {
            _interactRepository = interactRepository;
            _questionRepository = questionRepository;
            _answerRepository = answerRepository;
            _logger = logger;
            _mapper = mapper;
        }

        public async Task<ApiResult<bool>> Handle(CreateConsultInteractCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始创建用户互动，用户ID：{UserId}，对象类型：{ObjType}，对象ID：{ObjId}，操作类型：{Action}",
                    request.UserId, request.ObjType, request.ObjId, request.Action);

                // 检查是否已存在相同的互动记录
                var existingInteract = await _interactRepository.GetAll()
                    .Where(i => !i.IsDeleted && i.UserId == request.UserId && i.ObjType == request.ObjType && 
                           i.ObjId == request.ObjId && i.Action == request.Action)
                    .FirstOrDefaultAsync(cancellationToken);

                // 如果已存在互动记录，则取消互动（取消点赞/收藏等）
                if (existingInteract != null)
                {
                    existingInteract.IsDeleted = true;
                    await _interactRepository.UpdateAsync(existingInteract);

                    // 减少对应对象的计数
                    await UpdateCountAsync(request, -1, cancellationToken);

                    return new ApiResult<bool>
                    {
                        Code = ApiEnum.Success,
                        Msg = "取消互动成功",
                        Data = true
                    };
                }

                // 创建新的互动记录
                var interact = new ConsultInteract
                {
                    UserId = request.UserId,
                    ObjType = request.ObjType,
                    ObjId = request.ObjId,
                    Action = request.Action,
                    CreatedAt = DateTime.Now
                };

                await _interactRepository.CreateAsync(interact);

                // 增加对应对象的计数
                await UpdateCountAsync(request, 1, cancellationToken);

                return new ApiResult<bool>
                {
                    Code = ApiEnum.Success,
                    Msg = "创建互动成功",
                    Data = true
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建用户互动时发生异常");
                return new ApiResult<bool>
                {
                    Code = ApiEnum.Error,
                    Msg = "创建用户互动失败：" + ex.Message,
                    Data = false
                };
            }
        }

        /// <summary>
        /// 更新对应对象的计数（点赞数等）
        /// </summary>
        private async Task UpdateCountAsync(CreateConsultInteractCommand request, int change, CancellationToken cancellationToken)
        {
            // 仅处理点赞操作的计数更新
            if (request.Action != "like")
            {
                return;
            }

            // 根据对象类型更新相应的计数
            switch (request.ObjType)
            {
                case "question":
                    var question = await _questionRepository.GetAll()
                        .FirstOrDefaultAsync(q => q.Id == request.ObjId && !q.IsDeleted, cancellationToken);
                    if (question != null)
                    {
                        question.LikeCnt += change;
                        await _questionRepository.UpdateAsync(question);
                    }
                    break;

                case "answer":
                    var answer = await _answerRepository.GetAll()
                        .FirstOrDefaultAsync(a => a.Id == request.ObjId && !a.IsDeleted, cancellationToken);
                    if (answer != null)
                    {
                        answer.LikeCnt += change;
                        await _answerRepository.UpdateAsync(answer);
                    }
                    break;
            }
        }
    }
} 